package com.gframework.util.compress;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * ZLib压缩和解压缩工具类.<br/>
 * XXX 可以更改为不要以工具类的形式出现
 * 
 * @since 1.0.0
 * @author Ghwolf
 *
 */
public final class ZLibUtil {
	private ZLibUtil(){}
	/**
	 * zlib压缩方法.<br/>
	 * @param data 要压缩的数据
	 * @return 返回压缩后的结果
	 */
	public static byte[] compresser(byte[] data) {
		Deflater compresser = new Deflater();
		compresser.reset();
		compresser.setInput(data);
		compresser.finish();
		byte[] b = new byte[10024];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		do {
			int i = compresser.deflate(b);
			out.write(b, 0, i);
		}while(!compresser.finished());
		byte[] ret = out.toByteArray();
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			throw new CompressionException(e);
		}
		return ret;
	}
	
	/**
	 * zlib解压缩方法.<br/>
	 * 如果数据原本不是通过zlib算法压缩的，则会返回null
	 * @param data 要解压的数据
	 * @return 返回解压后的数据，如果解压错误则返回看null
	 */
	public static byte[] decompresser(byte[] data) {
		Inflater decompresser = new Inflater();
		decompresser.reset();
		decompresser.setInput(data);
		byte[] result = new byte[1024];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			do {
				int i = decompresser.inflate(result);
				out.write(result, 0, i);
			} while(!decompresser.finished());
			decompresser.end();
			return out.toByteArray();
		} catch (DataFormatException e) {
			throw new DecompressionException(e);
		} finally {
			try {
				out.flush();
				out.close();
			} catch (IOException e) {
				// ignore
			}
		}
	}
}
